﻿using QWManage.DAL;
using QWManage.Excel;
using QWManage.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;

namespace QWManage
{
    public partial class FrmBlockedUsers : Form
    {
        private DataTable _dataTable = new DataTable("黑名单");
        public int _matched = 0;
        public FrmBlockedUsers()
        {
            InitializeComponent();
        }

        private void FrmBlockedUsers_Load(object sender, EventArgs e)
        {
            lvUsers.Items.Clear();
            lvUsers.View = View.Details;
            lvUsers.FullRowSelect = true;
            lvUsers.MultiSelect = true;
            lvUsers.Columns.Clear();
            lvUsers.Columns.Add(new ColumnHeader() { Name = "Name", Text = "客户名称", Width = 300 });
            lvUsers.Columns.Add(new ColumnHeader() { Name = "SName", Text = "共享人", Width = 300 });
            lvUsers.Columns.Add(new ColumnHeader() { Name = "STime", Text = "共享时间", Width = 300 });

            lvUsers.Columns.Add(new ColumnHeader() { Name = "Type", Text = "类型", Width = 50 });
            lvUsers.Columns.Add(new ColumnHeader() { Name = "Unionid", Text = "Unionid", Width = 200 });
            lvUsers.Columns.Add(new ColumnHeader() { Name = "Avatar", Text = "Avatar", Width = 300 });
            lvUsers.VirtualMode = true;

            _dataTable.Columns.Add("Name", System.Type.GetType("System.String"));
            _dataTable.Columns.Add("SName", System.Type.GetType("System.String"));
            _dataTable.Columns.Add("STime", System.Type.GetType("System.DateTime"));

            _dataTable.Columns.Add("Type", System.Type.GetType("System.Int32"));

            _dataTable.Columns.Add("Unionid", System.Type.GetType("System.String"));
            _dataTable.Columns.Add("Avatar", System.Type.GetType("System.String"));

            btnLoadData_Click(null, null);
            lblStatus.Text = $"共 {_dataTable.Rows.Count} 条记录，已经匹配 {_matched} 条记录";
            // 绑定事件
            lvUsers.RetrieveVirtualItem += ListView_RetrieveVirtualItem;
            lvUsers.ColumnClick += LvUsers_ColumnClick;
        }

        private void LvUsers_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            try
            {
                foreach (Control control in this.Controls) control.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                if (lvUsers.Items.Count == 0) return;
                ColumnHeader ch = lvUsers.Columns[e.Column];
                string orderType = ch.Tag == null ? "" : (string)ch.Tag;
                if (orderType == "" || orderType == "ASC")
                    orderType = "DESC";
                else
                    orderType = "ASC";
                ch.Tag = orderType;
                string fieldName = ch.Name;
                DataTable newTable = _dataTable.Clone();
                DataRow[] drArr = _dataTable.Select("", fieldName + " " + orderType);
                foreach (DataRow dr in drArr)
                {
                    newTable.ImportRow(dr);
                }
                newTable.AcceptChanges();
                _dataTable = newTable;
                lvUsers.VirtualListSize = _dataTable.Rows.Count;
                lvUsers.Invalidate();
            }
            finally
            {
                foreach (Control control in this.Controls) control.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void ListView_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
        {
            DataRow dr = _dataTable.Rows[e.ItemIndex];
            ListViewItem lvItem = new ListViewItem(dr["Name"] == DBNull.Value ? "" : dr["Name"].ToString());
            lvItem.SubItems.Add(dr["SName"] == DBNull.Value ? "" : dr["SName"].ToString());
            lvItem.SubItems.Add(dr["STime"] == DBNull.Value ? "" : ((DateTime)dr["STime"]).ToString("yyyy年MM月dd日 HH:mm"));
            lvItem.SubItems.Add(dr["Type"] == DBNull.Value ? "" : dr["Type"].ToString());
            lvItem.SubItems.Add(dr["Unionid"] == DBNull.Value ? "" : dr["Unionid"].ToString());
            lvItem.SubItems.Add(dr["Avatar"] == DBNull.Value ? "" : dr["Avatar"].ToString());
            e.Item = lvItem;
        }

        private void btnExportExcel_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "表格文档(*.xlsx)|*.xlsx";
            dlg.InitialDirectory = Environment.CurrentDirectory;
            try
            {
                if (dlg.ShowDialog() != DialogResult.OK) return;
                DataRow[] drs = _dataTable.Select("Type is not null or Unionid is not null");
                if (drs.Length == 0)
                {
                    MessageBox.Show("匹配到的黑名单数据为空，请匹配好后再试", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                DataTable table = drs.CopyToDataTable();
                table.TableName = "黑名单";
                DataTableToExcel dataTableToExcel = new Excel.DataTableToExcel(table, dlg.FileName);
                dataTableToExcel.CreateExcel();
                MessageBox.Show("导出成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                Logs.LogMgr.Log(ex);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnLoadData_Click(object sender, EventArgs e)
        {
            _dataTable.Rows.Clear();

            BlockedDAL blockedUserDAL = new BlockedDAL();
            CustomerDAL customerDAL = new CustomerDAL();
            List<CustomerInfo> customerInfos = customerDAL.GetCustomerInfos();
            Dictionary<string, CustomerInfo> dic = new Dictionary<string, CustomerInfo>();
            foreach (CustomerInfo customerInfo in customerInfos)
            {
                string key = customerInfo.Avatar;
                if (!dic.ContainsKey(key))
                {
                    dic.Add(key, customerInfo);
                }
            }

            List<BlockedInfo> blockedUsers = blockedUserDAL.GetBlockedUserInfos();
            foreach (BlockedInfo blockedUserInfo in blockedUsers)
            {
                DataRow dr = _dataTable.NewRow();
                dr["Name"] = blockedUserInfo.Name;
                dr["SName"] = blockedUserInfo.SName;
                dr["STime"] = blockedUserInfo.STime;
                dr["Avatar"] = blockedUserInfo.Avatar;
                string key = blockedUserInfo.Avatar;
                if (dic.ContainsKey(key))
                {
                    CustomerInfo customerInfo = dic[key];
                    dr["Type"] = customerInfo.Type;
                    dr["Unionid"] = customerInfo.Unionid;
                    _matched++;
                }
                _dataTable.Rows.Add(dr);
            }

            lvUsers.VirtualListSize = _dataTable.Rows.Count;
            lvUsers.Invalidate();
        }
    }
}
